package com.mxm.mirai.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.mxm.mirai.dao.Bilibili;
import com.mxm.mirai.dao.Botbilibili;
import com.mxm.mirai.dao.Botbilibilijson;
import com.mxm.mirai.mapper.BilibiliMapper;
import com.mxm.mirai.service.BilibiliService;
import net.dreamlu.mica.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 漫小猫
 * @since 2020-09-24
 */
@Service
public class BilibiliServiceImpl extends ServiceImpl<BilibiliMapper, Bilibili> implements BilibiliService {

    @Autowired
    BilibiliMapper bilibiliMapper;

    @Override
    public Botbilibili getbilibilivideo(){
        String json = null;
        Botbilibili bili =null;
        try {
            json = HttpRequest.get("https://bangumi.bilibili.com/web_api/timeline_global")
                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36")
                    .connectTimeout(Duration.ofSeconds(40))
                    .execute().asString();
        }catch (Exception e){
            return null;
        }
        SimpleDateFormat df1 = new SimpleDateFormat("M-d");//设置日期格式
        SimpleDateFormat df2 = new SimpleDateFormat("HH:mm");//设置日期格式
        Date time = new Date();//获取当前系统时间
//         System.out.println(json);
        Botbilibilijson bb = new Gson().fromJson(json, Botbilibilijson.class);
//         System.out.println(bb.getMessage());
        for (Botbilibilijson.ResultBean bs:bb.getResult()) {
            for (Botbilibilijson.ResultBean.SeasonsBean bx:bs.getSeasons()) {
//                System.out.println(bx.getTitle()+"|"+df1.format(time)+"-"+bs.getDate()
//                +"|"+bx.getIs_published()+"-1|"+df2.format(time)+"-"+bx.getPub_time()+"|"
//                +bilibiliMapper.getBiliBiliByAv()+"-"+bx.getSeason_id());
                            //判断时间是否相同
                if(df1.format(time).equals(bs.getDate())
                        && bx.getIs_published() ==1//判断published是否等于1
                        && df2.format(time).equals(bx.getPub_time())//判断时间是否相同
                        && bilibiliMapper.getBiliBiliByAv() != bx.getSeason_id()){//判断数据库av是否相同
                    bilibiliMapper.UpdateBiliBiliByAv(bx.getSeason_id());
                    bili = new Botbilibili();
                    bili.setImg(bx.getCover());
                    bili.setTitle(bx.getTitle());
                    bili.setPub_index(bx.getPub_index());
                    bili.setPub_time(bx.getPub_time());
                    bili.setUrl("https://www.bilibili.com/bangumi/play/ep"+bx.getEp_id());
                    return bili;
                }
            }
        }
        return null;
    }
}
